package com.woniuxy.util;

import com.woniuxy.entity.po.JobBean;
import org.quartz.*;

/**
 * @BelongsProject: quartzStudy
 * @BelongsPackage: com.woniuxy.utils
 * @Author: Quan
 * @Date: 2025/3/4 17:45
 */
public class JobUtils {
	/**
	 * @Description: 生成一个定时任务
	 * @Param: scheduler - [Scheduler] 调度器
	 * @Param: jobBean - [JobBean] 任务Bean
	 * @Author: Quan
	 * @Date: 2025/3/4
	 */
	public static void createJob(Scheduler scheduler, JobBean jobBean) throws ClassNotFoundException, SchedulerException {

		Class<? extends Job> jobClass = (Class<? extends Job>) Class.forName(jobBean.getJobClass());
		JobDetail jobDetail = JobBuilder.newJob(jobClass)
				.storeDurably() // 持久化
				.withIdentity(jobBean.getJobName()) // 唯一标识
				.usingJobData("count", 1)  // （共享）数据的初始化
				.build();
		Trigger trigger = TriggerBuilder.newTrigger()
				.forJob(jobDetail)
				.withIdentity(jobBean.getJobName() + "_trigger")  // 唯一标识
				.withSchedule(CronScheduleBuilder.cronSchedule(jobBean.getCronExpression())) // 指定事件规则，cro表达式
				.build();
		scheduler.scheduleJob(jobDetail, trigger);
	}

	/**
	 * @Description: 将某个任务进行暂停
	 * @Param: scheduler - [Scheduler] 调度器
	 * @Param: jobName - [String] 任务Bean
	 * @Author: Quan
	 * @Date: 2025/3/4
	 */
	public static void pauseJob(Scheduler scheduler, String jobName) throws SchedulerException {
		JobKey jobKey = JobKey.jobKey(jobName);
		scheduler.pauseJob(jobKey);
	}

	public static void resumeJob(Scheduler scheduler, String jobName) throws SchedulerException {
		JobKey jobKey = JobKey.jobKey(jobName);
		scheduler.resumeJob(jobKey);
	}

	public static void deleteJob(Scheduler scheduler, String jobName) throws SchedulerException {
		JobKey jobKey = JobKey.jobKey(jobName);
		scheduler.deleteJob(jobKey);
	}

	/**
	 * @Description: 任务执行一次
	 * @Param: scheduler - [Scheduler]
	 * @Param: jobName - [String]
	 * @Author: Quan
	 * @Date: 2025/3/4
	 */
	public static void runOnceJob(Scheduler scheduler, String jobName) throws SchedulerException {
		JobKey jobKey = JobKey.jobKey(jobName);
		scheduler.triggerJob(jobKey);
	}

	/**
	 * @Description: 修改定时任务
	 * @Param: scheduler - [Scheduler] 调度器
	 * @Param: jobBean - [JobBean] 任务Bean
	 * @Author: Quan
	 * @Date: 2025/3/4
	 */
	public static void modifyJob(Scheduler scheduler, JobBean jobBean) throws SchedulerException {
		// 获取任务触发器的唯一标识
		TriggerKey triggerKey = TriggerKey.triggerKey(jobBean.getJobName() + "_trigger");
		// 通过唯一标识获取旧的触发器对象
		CronTrigger OldTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
		// 使用新的cron表达式构建新的触发器
		String newCron = jobBean.getCronExpression();
		Trigger newTrigger = OldTrigger.getTriggerBuilder()
				.withSchedule(CronScheduleBuilder.cronSchedule(newCron))
				.build();
		// 调度器更新任务的触发器
		scheduler.rescheduleJob(triggerKey, newTrigger);
	}
}
